package com.example.papercutting.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.papercutting.Data;
import com.example.papercutting.FoldedPaper;
import com.example.papercutting.R;
import com.example.papercutting.UnfoldPaper;
import com.example.papercutting.common.Item;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class CanvasActivity extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener {
    //    private final int FOLD_MODE = 0;
    private final int CUT_MODE = 1;
    private final int UNFOLD_MODE = 2;
    private int mode;
    private int width, height, x, y, r;
    //    private int foldNumber = 0 ;//记录折叠次数
    private static ArrayList<Item> savedWorks = new ArrayList<>(); // 保存所有创作完的作品
    private int division; // 上一个页面传来的等分数
    private int color;
    private String workName;

    private EditText editText;
    private FoldedPaper foldedPaper;
    private UnfoldPaper unfoldPaper;
    private ImageView imageView;
    private ImageButton foldButton, cutButton, unfoldButton, backButton, completeButton;
    private Button submit_button;

    private ImageButton undoButton, redoButton;

    private ArrayList<Bitmap> snapshots = new ArrayList<>(); // 保存操作快照的列表
    private int currentSnapshotIndex = -1; // 指针，初始化为-1，表示无操作


    private ConstraintLayout editLayout, completeLayout;
    private Bitmap foldPaperBitmap, cutPaperBitmap, unfoldPaperBitmap;
    private Canvas foldPaperCanvas, cutPaperCanvas, unfoldPaperCanvas;
    private Path cutPath = new Path();
    private Paint paperPaint, dashedPaint, cutPaint;

    @SuppressLint({"ClickableViewAccessibility", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canvas);
        Data.setCanvasSize(CanvasActivity.this);//创建Data对象获取屏幕大小

        // 从Intent获取等分数和颜色
        division = getIntent().getIntExtra("division", 8);
        color = getIntent().getIntExtra("color", Color.RED);
        if (division == 4) {
            Data.sweepAngle = 90;
        } else if (division == 6) {
            Data.sweepAngle = 60;
        } else if (division == 8) {
            Data.sweepAngle = 45;
        } else {
            Data.sweepAngle = 30;
        }

        width = Data.canvasWidth;
        height = Data.canvasHeight;
        x = width / 2;
        y = height / 2;
        r = (Math.min(width, height)) / 2;

        imageView = findViewById(R.id.canvas_iv);
//        foldButton = findViewById(R.id.canvas_fold);
        cutButton = findViewById(R.id.canvas_cut);
        unfoldButton = findViewById(R.id.canvas_unfold);
        backButton = findViewById(R.id.canvas_back);
        completeButton = findViewById(R.id.canvas_complete);
        editLayout = findViewById(R.id.constraintLayout_edit);
        completeLayout = findViewById(R.id.constraintLayout_complete);
        undoButton = findViewById(R.id.canvas_undo);
        redoButton = findViewById(R.id.canvas_redo);
        submit_button = findViewById(R.id.submit_button);

        foldPaperBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        cutPaperBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        unfoldPaperBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        editText = findViewById(R.id.text_input);

        paperPaint = new Paint();
        dashedPaint = new Paint();
        cutPaint = new Paint();
        setPaintEffect();

        foldPaperCanvas = new Canvas(foldPaperBitmap);
        cutPaperCanvas = new Canvas(cutPaperBitmap);
        unfoldPaperCanvas = new Canvas(unfoldPaperBitmap);


        foldPaperCanvas.drawColor(Data.transparentBackground);
        initialPaper();
        imageView.setBackgroundColor(Data.backgroundColor);

        foldedPaper = new FoldedPaper(CanvasActivity.this, color);
        foldedPaper.draw(cutPaperCanvas);
        Bitmap initmap = Bitmap.createBitmap(cutPaperBitmap);
        snapshots.add(initmap);
        currentSnapshotIndex++;
        unfoldPaper = new UnfoldPaper(CanvasActivity.this, cutPaperBitmap);

        imageView.setOnTouchListener(CanvasActivity.this);
//        foldButton.setOnClickListener(CanvasActivity.this);
        cutButton.setOnClickListener(CanvasActivity.this);
        unfoldButton.setOnClickListener(CanvasActivity.this);
        backButton.setOnClickListener(
                v -> {
                    // 切换到上一页面逻辑
                    Intent intent = new Intent(CanvasActivity.this, MainActivity.class);
                    startActivity(intent);
                    Toast.makeText(this, "上一页面", Toast.LENGTH_SHORT).show();
                }
        );
        completeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(CanvasActivity.this, "请为您的作品取个名字", Toast.LENGTH_SHORT).show();
                //让名字框显示,点击"完成"按钮完成整个创作过程
                editText.setVisibility(View.VISIBLE);
                submit_button.setVisibility(View.VISIBLE);

//                editLayout.setVisibility(View.INVISIBLE);
//                completeLayout.setVisibility(View.VISIBLE);
//                completeButton.setVisibility(View.INVISIBLE);
            }
        });
        undoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentSnapshotIndex > 0) { // 确保有可以撤销的操作
                    currentSnapshotIndex--;
                    cutPaperBitmap = Bitmap.createBitmap(snapshots.get(currentSnapshotIndex)); // 恢复快照
                    cutPaperCanvas.setBitmap(cutPaperBitmap); // 重设画布
                    unfoldPaper = new UnfoldPaper(CanvasActivity.this, cutPaperBitmap);

                    imageView.setImageBitmap(cutPaperBitmap); // 更新界面
                } else {
                    Toast.makeText(CanvasActivity.this, "没有更多操作可以撤销！", Toast.LENGTH_SHORT).show();
                }
            }
        });


        redoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentSnapshotIndex < snapshots.size() - 1) { // 确保有可以重做的操作
                    currentSnapshotIndex++;
                    cutPaperBitmap = Bitmap.createBitmap(snapshots.get(currentSnapshotIndex)); // 恢复快照
                    cutPaperCanvas.setBitmap(cutPaperBitmap); // 重设画布
                    imageView.setImageBitmap(cutPaperBitmap); // 更新界面
                } else {
                    Toast.makeText(CanvasActivity.this, "没有更多操作可以重做！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        submit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取作品名
                workName = editText.getText().toString().trim();
                // 使用 Date 获取当前时间
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = dateFormat.format(date);
                //点击确定按钮后,将对象保存,先构造
                Item item = new Item(unfoldPaperBitmap, currentTime, workName);
                savedWorks.add(item);
                Toast.makeText(CanvasActivity.this, "作品 " + workName + " 保存成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(CanvasActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });


        mode = CUT_MODE;
//        foldButton.setClickable(false);
//        foldButton.setBackgroundColor(Data.checkedBackground);
        cutButton.setClickable(false);
        cutButton.setBackgroundColor(Data.checkedBackground);
        // todo 设为true实时预览
        unfoldButton.setClickable(true);

    }

    public static ArrayList<Item> getSavedWorks() {
        return savedWorks;
    }


    public void setPaintEffect() {
        //红笔
        paperPaint.setColor(color);
        paperPaint.setAntiAlias(true);
        //虚线笔
        dashedPaint.setColor(Color.GRAY);
        dashedPaint.setStrokeWidth(20);
        dashedPaint.setPathEffect(new DashPathEffect(new float[]{20, 20}, 0));
        dashedPaint.setAntiAlias(true);
        //剪刀
        cutPaint.setColor(Data.backgroundColor);
        cutPaint.setStrokeWidth(Data.paintWidth);
        cutPaint.setAntiAlias(true);
    }

    public void initialPaper() {
        foldPaperCanvas.drawColor(0, PorterDuff.Mode.CLEAR); // 清空画布
        float angleStep = 360.0f / division; // 每一份的角度
        float offsetY = 200; // 圆心向下移动的偏移量，可以根据需要调整

        // 调整 RectF 的 y 坐标，使圆心向下移动
        RectF rectF = new RectF(x - r, y - r + offsetY, x + r, y + r + offsetY); // 移动圆心

        // 从 -90° 开始绘制竖直方向的扇形
        foldPaperCanvas.drawArc(rectF, -90, angleStep, true, paperPaint);

        imageView.setImageBitmap(foldPaperBitmap); // 将绘制结果显示在ImageView上
    }


    private boolean isStart = false, inRange = true;
    float startX, startY, endX, endY, eventX, eventY;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        eventX = event.getX();
        eventY = event.getY();
        switch (mode) {
            /**case FOLD_MODE:
             switch (foldNumber) {
             case 0://第一次折
             switch (event.getAction()) {
             case MotionEvent.ACTION_DOWN:
             startX = eventX;
             startY = eventY;
             isStart = ((eventX > x + 0.75*r) || (eventX < x - 0.75*r)) && eventY > y - 100 && eventY < y + 100;
             break;
             case MotionEvent.ACTION_MOVE:
             if (isStart) inRange = inRange && eventY > y - 100 && eventY < y + 100;
             break;
             case MotionEvent.ACTION_UP:
             if (isStart && inRange && (eventX - startX > 1.5 * r || startX - eventX > 1.5 * r)) {
             isStart = false;
             inRange = true;
             foldNumber++;
             drawFoldPaper(foldNumber);
             }
             break;
             }
             break;
             case 1://第二次折
             switch (event.getAction()){
             case MotionEvent.ACTION_DOWN:
             startX = eventX;
             startY = eventY;
             isStart = ((eventX>x-100&&eventX<x+100)&&(eventY>y-100&&eventY<y+100))||
             ((eventX>x+r/2-100&&eventX<x+r/2+100)&&(eventY>y-r/2*1.732-100&&eventY<y-r/2*1.732+100));
             break;
             case MotionEvent.ACTION_MOVE:
             if(isStart) inRange = inRange&&(eventY-y-1.732*(eventX-x)>-100&&eventY-y-1.732*(eventX-x)<100);
             break;
             case MotionEvent.ACTION_UP:
             if (isStart&&(eventX-startX>0.4*r||startX-eventX>0.4*r)){
             isStart = false;
             inRange = true;
             foldNumber++;
             drawFoldPaper(foldNumber);
             }
             break;
             }
             break;
             case 2://第三次折
             switch (event.getAction()){
             case MotionEvent.ACTION_DOWN:
             startX = eventX;
             startY = eventY;
             isStart = ((eventX>x-100&&eventX<x+100)&&(eventY>y-100&&eventY<y+100))||
             ((eventX>x-r/2-100&&eventX<x-r/2+100)&&(eventY>y-r/2*1.732-100&&eventY<y-r/2*1.732+100));
             break;
             case MotionEvent.ACTION_MOVE:
             if(isStart) inRange = inRange&&(eventY-y+1.732*(eventX-x)>-100&&eventY-y+1.732*(eventX-x)<100);
             break;
             case MotionEvent.ACTION_UP:
             if (isStart&&(eventX-startX>0.4*r||startX-eventX>0.4*r)){
             isStart = false;
             inRange = true;
             foldNumber++;
             drawFoldPaper(foldNumber);
             }
             break;
             }
             break;
             case 3://第四次折
             switch (event.getAction()){
             case MotionEvent.ACTION_DOWN:
             startX = eventX;
             startY = eventY;
             isStart = ((eventX>x-100&&eventX<x+100)&&(eventY>y-100&&eventY<y+100))||
             ((eventX>x-100&&eventX<x+100)&&(eventY>y-r-100&&eventY<y-r+100));
             break;
             case MotionEvent.ACTION_MOVE:
             if(isStart) inRange = inRange&&(eventX > x - 100 && eventX < x + 100);
             break;
             case MotionEvent.ACTION_UP:
             if (isStart&&(eventY-startY>0.4*r||startY-eventY>0.4*r)){
             isStart = false;
             inRange = true;
             foldNumber++;
             drawFoldPaper(foldNumber);
             cutButton.setClickable(true);
             Toast.makeText(CanvasActivity.this,"点击“裁剪”按钮开始裁剪",Toast.LENGTH_SHORT).show();
             }
             break;
             }
             break;
             }
             break; */
            case CUT_MODE:
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下时记录点击位置
                        startX = eventX;
                        startY = eventY;
                        cutPath.moveTo(startX, startY);
                        break;
                    case MotionEvent.ACTION_MOVE://移动时画出路线，并记录
                        endX = eventX;
                        endY = eventY;
                        cutPath.lineTo(endX, endY);
                        cutPaperCanvas.drawLine(startX, startY, endX, endY, cutPaint);
                        startX = endX;
                        startY = endY;
                        break;
                    case MotionEvent.ACTION_UP://把路线闭合形成镂空效果
                        cutPath.lineTo(endX, endY);
                        cutPath.close();
                        cutPaperCanvas.drawPath(cutPath, cutPaint);

//                        redoStack.clear(); // 清空 redoStack
                        saveSnapshot(); // 保存快照

                        cutPath.reset(); // 清空当前路径，避免累积

                        break;
                }
                imageView.setImageBitmap(cutPaperBitmap);
                break;
            default:
                break;
        }
        return true;
    }

    private void saveSnapshot() {
        // 截取当前 cutPaperBitmap 的快照
        Bitmap snapshot = Bitmap.createBitmap(cutPaperBitmap);
        // 如果当前指针不是最后一个元素，移除后续元素（redo 的分支会被覆盖）
        while (currentSnapshotIndex < snapshots.size() - 1) {
            snapshots.remove(snapshots.size() - 1);
        }
        // 保存新的快照，并更新指针
        snapshots.add(snapshot);
        currentSnapshotIndex++;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
//        foldButton.setClickable(true);
        cutButton.setClickable(true);
        unfoldButton.setClickable(true);
//        v.setClickable(false);
//        foldButton.setBackgroundColor(Data.transparentBackground);
        cutButton.setBackgroundColor(Data.transparentBackground);
        unfoldButton.setBackgroundColor(Data.transparentBackground);
        v.setBackgroundColor(Data.checkedBackground);
        switch (v.getId()) {
            case R.id.canvas_cut:
                mode = CUT_MODE;
                completeButton.setVisibility(View.INVISIBLE);
                imageView.setImageBitmap(cutPaperBitmap);
                break;
            case R.id.canvas_unfold:
                mode = UNFOLD_MODE;
                unfoldPaper.draw(unfoldPaperCanvas);
                completeButton.setVisibility(View.VISIBLE);
                imageView.setImageBitmap(unfoldPaperBitmap);
                break;
        }
    }
}